<template>
  <div class="upload_file">
    <el-upload
      v-if="props.show"
      :multiple="true"
      :headers="headers"
      :action="uploadUrl"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleFileSuccess"
      name="files"
      :limit="props.limit">
      <el-button type="info">{{ config.button.text.upload }}</el-button>
    </el-upload>

    <div
      class="image_area"
      v-if="imageList.length > 0">
      <div
        class="image_list"
        v-for="(item, index) in imageList"
        :key="item.uuid">
        <el-dropdown trigger="click">
          <el-icon style="color:#409eff">
            <Tools />
          </el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="downLoad(item)">{{ config.button.text.download }}</el-dropdown-item>
              <el-dropdown-item
                v-if="props.show"
                @click="updateFileName(item)">
                更改文件名
              </el-dropdown-item>
              <el-dropdown-item
                v-if="props.show"
                @click="handleRemove(index)">
                {{ config.button.text.delete }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="item.uploadFileName"
          placement="top">
          <span @click="previewImg(index)">{{ item.uploadFileName }}</span>
        </el-tooltip>
      </div>
    </div>

    <el-image-viewer
      v-if="showPreview"
      :url-list="srcList"
      show-progress
      :initial-index="urlIndex"
      @close="showPreview = false" />

    <el-dialog
      v-model="visibility"
      title="更改文件名"
      append-to-body
      draggable
      :close-on-click-modal="false">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-width="config.form.label.width"
        status-icon>
        <el-form-item
          label="文件名"
          prop="uploadFileName">
          <el-input
            v-model="formData.uploadFileName"
            placeholder="文件名"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
          <el-button
            type="primary"
            @click="saveEvent">
            {{ config.button.text.save }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import loadon from "@/common/element-plus/loadon";
import ApiBusinessFile from "@/api/modules/business-file";
import message from "@/common/element-plus/message";
import confirm from "@/common/element-plus/confirm";
import { useValidator } from "@/hooks/useValidator";

// 上传文件参数
const token = localStorage.getItem(localStorage.getItem("tokenName"))
const uploadUrl = ref(import.meta.env.VITE_API + "/businessFile/uploadFile");
const headers = ref({});
if (token) {
  headers.value["yg-token"] = token;
}
// 上传的文件列表
const fileList = ref([]);
// 查询的文件列表(名字等信息)
const imageList = ref([]);
// 预览图片(url)
const srcList = ref([])
const showPreview = ref(false)
const urlIndex = ref(0)
// 表单
const formData = ref({})
const formRef = ref()
const { required, validate, clearValidate } = useValidator()
const formRules = {
  uploadFileName: [required("文件名")],
}
const visibility = ref(false)

const props = defineProps(["limit", "fileUuids", "show"])
const emits = defineEmits(["success", "deleteFile"])

// 预览图片
const previewImg = (index) => {
  showPreview.value = true
  urlIndex.value = index
}

// 下载图片
const downLoad = async (item) => {
  const data = await ApiBusinessFile.downloadFileByUuid(item.fileUuid)
  let downloadElement = document.createElement("a");
  downloadElement.href = data;
  downloadElement.download = item.uploadFileName; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(data); //释放掉blob对象
}

// 更改文件名
const updateFileName = (item) => {
  setTimeout(() => {
    clearValidate(formRef.value)
  })
  visibility.value = true
  formData.value = Object.assign({}, item)
  formData.value.uploadFileName = item.uploadFileName.split(".")[0]
  formData.value.suffix = "." + item.uploadFileName.split(".")[1]
}

// 保存更改的文件名
const saveEvent = async () => {
  await validate(formRef.value)
  await ApiBusinessFile.updateFileName({
    uploadFileName: formData.value.uploadFileName + formData.value.suffix,
    fileUuid: formData.value.fileUuid
  })
  await getImageList(fileList.value);
  visibility.value = false
  message.success()
}

// 删除图片
const handleRemove = (index) => {
  confirm.delete().then(data => {
    if (data === "confirm") {
      emits("deleteFile", imageList.value[index].fileUuid)
      fileList.value.splice(index, 1);
      imageList.value.splice(index, 1);
    }
  })
}

// 上传前的钩子函数，显示加载状态
const beforeUpload = () => {
  loadon.show()
  // 返回 true 允许文件上传
  return true;
};

// 处理文件成功回调
const handleFileSuccess = async (res) => {
  loadon.hide()
  if (res?.code === 200) {
    fileList.value.push(res.data[0].fileUuid);
    await getImageList(fileList.value);
    emits("success", res.data[0].fileUuid)
  } else {
    message.error(res?.message);
  }
}

// 获取文件列表
const getImageList = async (data) => {
  const res = await ApiBusinessFile.selectListByUuidList(data);
  imageList.value = res.data;
  srcList.value = []
  imageList.value.forEach((item) => {
    srcList.value.push(import.meta.env.VITE_API  + `/businessFile/downloadFileByUuid?fileUuid=${item.fileUuid}`)
  })
}

watch(() => props.fileUuids, async (newVal) => {
  if (newVal) {
    await getImageList(newVal)
    fileList.value = newVal
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.upload_file {
  width: 100%;

  .image_area {
    max-height: 300px;
    overflow-x: auto;
    border: 1px solid #dcdfe6;
    padding: 10px;
    margin-top: 8px;
    border-radius: 6px;

    .image_list {
      color: #409eff;
      display: flex;
      align-items: center;
      cursor: pointer;
      border-bottom: 1px solid #dcdfe6;

      .el-icon {
        margin-right: 5px;
      }

      span {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1; //行数
        -webkit-box-orient: vertical;
      }
    }
  }
}
</style>